<template>
  <div class="register">
    <a-form
      :model="form"
      :rules="rules"
      :style="{ width: '450px' }"
      @submit="handleSubmit"
    >
      <a-form-item>
        <a-space>
          <h1>用户注册</h1>
          <a-button
            html-type="submit"
            style="background-color: green; color: white"
            >注册</a-button
          >
          <a-button
            style="background-color: #165dff; color: white"
            @click="$router.push('/user/login')"
            >登录</a-button
          >
        </a-space>
      </a-form-item>
      <a-form-item field="userAccount" label="账号">
        <a-input v-model="form.userAccount" placeholder="请输入你的账号" />
      </a-form-item>
      <a-form-item
        field="userPassword"
        tooltip="请输入不少于8位密码"
        label="密码"
      >
        <a-input-password
          v-model="form.userPassword"
          placeholder="请输入你的密码"
        />
      </a-form-item>
      <a-form-item
        field="checkPassword"
        label="确认密码"
        validate-trigger="blur"
      >
        <a-input-password
          v-model="form.checkPassword"
          placeholder="请再次输入你的密码"
        />
      </a-form-item>
    </a-form>
  </div>
</template>
<script setup lang="ts">
import { reactive } from "vue";
import { UserControllerService } from "../../../generated";

import message from "@arco-design/web-vue/es/message";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
const form = reactive({
  userAccount: "",
  userPassword: "",
  checkPassword: "",
  isRead: false,
});
const store = useStore();
const router = useRouter();
//提交表单
const handleSubmit = async (data: any) => {
  data = data.values;
  if (data.userAccount && data.userPassword && data.checkPassword) {
    const res = await UserControllerService.userRegisterUsingPost(form);
    if (res.code === 0) {
      await store.dispatch("user/getLoginUser");
      await router.push({
        path: "/user/login",
        replace: true,
      });
    } else {
      message.error("注册失败:" + res.message);
    }
  }
};
const rules = {
  userAccount: [
    {
      required: true,
      message: "账号不能为空",
    },
  ],
  userPassword: [
    {
      required: true,
      message: "密码不能为空",
    },
  ],
  checkPassword: [
    {
      required: true,
      message: "密码不能为空",
    },
    {
      validator: (value: any, cb: (arg0: string | undefined) => void) => {
        if (value !== form.userPassword) {
          cb("两次密码不一样");
        }
      },
    },
  ],
};
</script>
<style scoped>
.register {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
